import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ConfigService } from './config.service';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class TableDictService {
  private _map: any = {};
  private cache = false;
  constructor(private http: Http, private config: ConfigService) {
  }
  public get(code: string, primeng?: boolean): Observable<any> {
    if (this._map[code] && this.cache) {
      return Observable.fromPromise(Promise.resolve(this._map[code]));
    }
    const url = this.config.get('url') + '?service=TableDictService&method=getDictList';
    return this.http.post(url, { code: code }).map((resp: Response) => {
      const result = resp.json();
      if (result.code === '0000') {
        const r = [];
        result.info.forEach((a: any) => {
          if (primeng) {
            r.push({ value: a.value, label: a.label });
          } else {
            r.push({ id: a.value, text: a.label });
          }

        });
        if (this.cache) {
          this._map[code] = r;
        }

        return r;
      }
    });
  }
  public getProvince(slaLevel?: string): Observable<any> {
    let url, options;
    if (slaLevel) {
      url = this.config.get('url') + '?service=CountyInfoService&method=getProvinceInfoBySlaLevel';
      options = { slaLevel: slaLevel };
    } else {
      url = this.config.get('url') + '?service=CountyInfoService&method=getCountyInfoByLevel';
      options = { level: '1' };
    }

    return this.http.post(url, options).map((resp: Response) => {
      const result = resp.json();
      if (result.code === '0000') {
        const r = [];
        result.info.forEach((a: any) => {
          r.push({ id: a.countyId, text: a.countyName });
        });
        return r;
      }
    });
  }
  public getCity(provinceId: string, slaLevel?: string): Observable<any> {
    let url, options;
    if (slaLevel) {
      url = this.config.get('url') + '?service=CountyInfoService&method=getCityInfoBySlaLevel';
      options = { provinceId: provinceId, slaLevel: slaLevel };
    } else {
      url = this.config.get('url') + '?service=CountyInfoService&method=getCountyInfoByParent';
      options = { parentId: provinceId };
    }

    return this.http.post(url, options).map((resp: Response) => {
      const result = resp.json();
      if (result.code === '0000') {
        const r = [];
        result.info.forEach((a: any) => {
          r.push({ id: a.countyId, text: a.countyName });
        });
        return r;
      }
    });
  }
}
